<?php
require_once 'xs_sdk/lib/XS.php';
require_once 'db.php';
require_once 'Document.php';
require_once 'config.php';


class API
{
    /**
     * ElasticSearch搜索
     * @param $keyword
     * @param $rules
     * @param $limit
     * @param int $page
     */
    public function search2($keyword, $rules, $limit, $page = 1, $ids = array()) {
        global $database;

        if ($page < 1) {
            $page = 1;
        }

        if ($limit < 10) {
            $limit = 10;
        }

        $doc = new Document();
        $result = $doc->search($keyword, $rules, $limit, $page, $ids);

        $data = [
            "items" => [],
            "total" => $result['hits']['total']['value']
        ];

        foreach ($result['hits']['hits'] as $item) {
            $data['items'][] = $item['_source'];
        }

        // 处理行为分析
        $pid_arr = [];
        $search_history_data = [];

        foreach ($data['items'] as $item) {
            $pid_arr[] = $item['pid'];
        }

        // 处理过虑规则
        $customer_id = null;
        if (null != $rules && !empty($rules)) {
            foreach ($rules as $rule) {
                if (isset($rule['behavior'])) {
                    // 记录行为
                    $search_history_data[$rule['field']] = $rule['value'];
                }
            }
        }

        $search_history_data['pids'] = implode(",", $pid_arr);
        $search_history_data['created'] = date("Y-m-d H:i:s");

        // 记录用户行为，只记录前20条
        if ($page == 1) {
            if (isset($search_history_data['season']) && isset($search_history_data['year']) && isset($search_history_data['customer'])) {

                if (intval($search_history_data['customer']) != 216) {
                    $database->insert("search_history", $search_history_data);
                }
            }
        }

        return $data;
    }

    /**
     * 批量导入图片
     */
    public function importImages() {
        $redis = new Redis;
        $redis->connect('127.0.0.1', 6379);
        $redis->auth('harrypekey123');

        $this->redis_queue_send($redis, "-import-images", "do");
    }

    /**
     * 搜索花型
     * 关键词搜索的拼接规则,中间用英文空格隔开
     * 关键词 单属性值1 单属性值2 AND (多属性值1 OR 多属性值2 ) AND (多属性值A AND 多属性值B)
     * 过虑条件的使用，比如宽幅范围，花高
     * [
     *   {'field': 'widthheight', 'from': 1, 'to': 10},
     *   {'field': 'height', 'value': 5},
     *   {'field': 'search_way', 'value': '关键字搜索', 'behavior': true},
     *   {'field': 'staff', 'value': '业务员ID', 'behavior': true},
     *   {'field': 'extra', 'value': '用途:童装|质感:薄透|波边:单边,直边', 'behavior': true}
     * ]
     * @param $keyword 搜索关键词
     * @param $rule 搜索条件过滤
     * @param $limit 每页限制
     * @param $page 第几页
     * @return array
     */
    public function search($keyword, $rules, $limit, $page = 1) {
        global $database;
        $query = "";
        $xs = new XS('pattern');
        $search = $xs->search;

        if ($page < 1) {
            $page = 1;
        }

        if ($limit < 10) {
            $limit = 10;
        }

        // 搜索关键词
        if ($keyword != '') {
            $query = $keyword;
        } else {
            $query = 'all';
        }

        $search_history_data = [];

        // 处理过虑规则
        $customer_id = null;
        if (null != $rules && !empty($rules)) {
            foreach ($rules as $rule) {
                if (isset($rule['behavior'])) {
                    // 记录行为
                    $search_history_data[$rule['field']] = $rule['value'];

                    if ($rule['field'] == 'customer') {
                        $customer_id = $rule['value'];
                    }
                } else {
                    if (isset($rule['value'])) {
                        $query .= " " . $rule['field'] . ':' . $rule['value'];
                    }
                }
            }
        }

        // 处理封板
        if ($customer_id != null) {
            $customer = $database->get("customer", "*", [
                "aid" => $customer_id
            ]);

            if ($customer) {
                $sales_area = json_decode($customer['sales_area'], true);

                $area_arr = [];

                foreach ($sales_area as $area) {
                    if (count($area) == 1) {
                        $area_arr[] = '-' . $area[0] . $area[0];
                        $area_arr[] = '-' . $area[0];
                    } else {
                        foreach ($area as $k => $v) {
                            if ($k == 0) {
                                $area_arr[] = '-' . $v . $v;
                            } else {
                                $area_arr[] = '-' . $v;
                            }
                        }
                    }
                }

                $area_arr = array_unique($area_arr);

                $area_str = implode(" ", $area_arr);
                $query .= " " . $area_str;
            }
        }

//        echo $query;
        $search->setQuery($query);

//        echo $search->getQuery();

        if (null != $rules && !empty($rules)) {
            foreach ($rules as $rule) {
                if (isset($rule['from']) && isset($rule['to'])) {
                    if ($rule['form'] == 0) {
                        $rule['form'] = null;
                    }

                    if ($rule['to'] == 0) {
                        $rule['to'] = null;
                    }

                    $search->addRange($rule['field'], $rule['from'], $rule['to']);
                }
            }
        }

        $search->setSort('pid');
        $search->setLimit($limit, ($page - 1) * $limit);
        $docs = $search->search();
        $count = $xs->search->lastCount;

        $data = [
            "items" => [],
            "total" => $count
        ];

        $pid_arr = [];

        foreach ($docs as $doc) {
            $item = $doc->getFields();
//            unset($item["content"]);
            $data["items"][] = $item;
            $pid_arr[] = $item['pid'];
        }

        $search_history_data['pids'] = implode(",", $pid_arr);
        $search_history_data['created'] = date("Y-m-d H:i:s");

        // 记录用户行为，只记录前20条
        if ($page == 1) {
            if (isset($search_history_data['season']) && isset($search_history_data['year']) && isset($search_history_data['customer'])) {
                $database->insert("search_history", $search_history_data);
            }
        }

        return $data;
    }

    /**
     * 添加或者更新索引
     * @param $pid
     * @param $update
     */
    private function save($pid, $update) {
        global $database;

        $pattern = $database->get("pattern", "*", [
            'pid' => $pid
        ]);

        if ($pattern) {
            $xs = new XS('pattern');
            $index = $xs->index; // 获取 索引对象
            $doc = new XSDocument;

            // 设置基础数据
            $data = array(
                'pid' => $pattern['pid'],
                'title' => $pattern['title'],
                'content' => $pattern['title'],
                'picture' => $pattern['picture'],
                'weight' => $pattern['weight'],
                'height' => $pattern['height'],
                'widthheight' => $pattern['widthheight'],
                'widthlow' => $pattern['widthlow'],
                'no' => $pattern['no'],
                'component' => $pattern['component'],
                'series' => $pattern['series']
            );

            // 处理封板================= begin =========================
            $plates_out = [];
            $plates = json_decode($pattern['plates'], true);
            var_dump($pattern['plates']);
            foreach ($plates as $plate) {
                if (count($plate) == 1) {
                    $plates_out[] = $plate[0] . $plate[0];
                } else {
                    $plates_out[] = implode(',', $plate);
                }
            }

            if (count($plates_out) > 0) {
                $data['sealing'] = implode("|", $plates_out);
            }
            // 处理封板=================== end ===========================

            // 设置属性
            $properties = $database->select("pattern_property", "*", [
                'pid' => $pid
            ]);

            // 属性字段拼接
            $property_strings = '';

            foreach ($properties as $property) {
                $json = json_decode($property['property_value'], true);
                $value = $json['value'];

                if (is_array($value)) {
                    $property_strings .= ' ' . implode(',', $value);
                } else {
                    $property_strings .= ' ' . $value;
                }
            }

            $data['content'] .= 'all ' . $property_strings;

            $doc->setFields($data);

            try {
                if ($this->checkExists($pattern['pid'])) {
                    $index->update($doc)->flushIndex();
                } else {
                    $index->add($doc)->flushIndex();
                }
            } catch (Exception $e) {
                print_r($e);
            }

            return true;
        }

        return false;
    }

    /**
     * 添加索引,添加花型成功后传
     * @param $pid 花型ID
     * @param $pictures 5张图片地址，格式:path1|path2|path3
     */
    public function addIndex($pids) {
        global $database;
        $redis = new Redis;
        $redis->connect('127.0.0.1', 6379);
        $redis->auth('harrypekey123');
        $queue = '-pattern-add';

        $arr = explode(',', $pids);

        $items = $database->select("pattern", "*", ['pid' => $arr]);
        foreach ($items as $item) {
            $properties = $database->select("pattern_property", "*", [
                'pid' => $item['pid']
            ]);

            $item['properties'] = $properties;

            $this->redis_queue_send($redis, $queue, $item);
        }
    }

    /**
     * 更新花型数据后调用，更新索引
     * @param $pid 花型ID
     */
    public function updateIndex($pid) {
        //插入队列
        global $database;

        $redis = new Redis;
        $redis->connect('127.0.0.1', 6379);
        $redis->auth('harrypekey123');

        $queue = '-pattern-update';
        $item = $database->get("pattern", "*", ['pid' => $pid]);
        $properties = $database->select("pattern_property", "*", [
            'pid' => $pid
        ]);

        $item['properties'] = $properties;
        $this->redis_queue_send($redis, $queue, $item);
    }

    /**
     * 删除索引
     * @param $pid 花型ID
     */
    public function delIndex($no) {
        $doc = new Document();
        return $doc->delete($no);
    }

    /**
     * @param $path
     */
    public function imageSearch($path) {

        $post_data = [
            'file' => new \CURLFile(UPLOAD_DIR . $path),  //必须是绝对路径
        ];

        $rt = $this->curl_post('http://127.0.0.1:5001/uploader', $post_data);

        return $rt;
    }

    /**
     * 下单检测客户封板
     * @param $pids 花型ID数组,如[16,17,18,19]
     * @param $account_id 客户ID
     * @return array ['SHL-06','SHL-04']
     */
    public function checkBuy($pids, $account_id) {
        global $database;
        $query = "";
        $xs = new XS('pattern');
        $search = $xs->search;

        $pids_arr = [];

        foreach ($pids as $pid) {
            $pids_arr[] = 'pid:' . $pid;
        }

        $query = '(' . implode(' OR ', $pids_arr) . ')';

        // 处理封板
        $customer = $database->get("customer", "*", [
            "aid" => $account_id
        ]);

        if ($customer) {
            $sales_area = json_decode($customer['sales_area'], true);

            $area_arr = [];

            foreach ($sales_area as $area) {
                if (count($area) == 1) {
                    $area_arr[] = '-' . $area[0] . $area[0];
                    $area_arr[] = '-' . $area[0];
                } else {
                    $area_arr[] = '-' . $area[0] . $area[0];
                    $area_arr[] = '-' . $area[1];
                }
            }

            $area_arr = array_unique($area_arr);

            $area_str = implode(" ", $area_arr);
            $query .= " " . $area_str;
        }

        $search->setQuery($query);
        $docs = $search->search();

        $pids_result = [];
        foreach ($docs as $doc) {
            $item = $doc->getFields();
            $pids_result[] = $item['pid'];
        }

        $diff = array_diff($pids, $pids_result);

        $pids_arr = [];
        $nos = [];
        if (count($diff) > 0) {
            foreach ($diff as $pid) {
                $pids_arr[] = 'pid:' . $pid;
            }

            $query = '(' . implode(' OR ', $pids_arr) . ')';
            $search->setQuery($query);
            $docs = $search->search();

            foreach ($docs as $doc) {
                $item = $doc->getFields();

                $nos[] = $item['no'];
            }
        }

        return $nos;
    }

    public function updateIndexByNo($no, $picture, $thumb, $otherImages) {
        global $database;

        $pattern = $database->get("pattern", "*", [
            'no' => $no
        ]);

        if ($pattern) {
            $other = explode(',', $pattern['otherImg']);
            $otherNew = array_merge($other, $otherImages);
            $otherOut = array_unique($otherNew);

            $data = [
                'picture' => $picture,
                'picture_thumb' => $thumb,
                'otherImg' => implode(",", $otherOut)
            ];

            // 更新图片
            $database->update('pattern', $data, ['pid' => $pattern['pid']]);

            // 更新搜索引擎
            $this->updateIndex($pattern['pid']);
        }
    }

    /**
     * 判断索引是否存在
     * @param $pid
     */
    private function checkExists($pid) {
        $xs = new XS('pattern');
        $search = $xs->search;
        $search->setQuery('pid:' . $pid);
        $docs = $search->search();
        $search->setLimit(5);

        if ($search->lastCount) {
            return true;
        }

        return false;
    }

    private function redis_queue_send($redis, $queue, $data, $delay = 0) {
        $queue_waiting = '{redis-queue}-waiting'; //1.0.5版本之前为redis-queue-waiting
        $queue_delay = '{redis-queue}-delayed';//1.0.5版本之前为redis-queue-delayed

        $now = time();
        $package_str = json_encode([
            'id'       => rand(),
            'time'     => $now,
            'delay'    => 0,
            'attempts' => 0,
            'queue'    => $queue,
            'data'     => $data
        ]);
        if ($delay) {
            return $redis->zAdd($queue_delay, $now + $delay, $package_str);
        }
        return $redis->lPush($queue_waiting.$queue, $package_str);
    }

    private function curl_post($url,$post_data)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);
        return  $output;
    }
}